<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="题目ID" prop="questionId">
          <el-input
            v-model="queryParams.questionId"
            placeholder="请输入题目ID"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="题目内容" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入题目内容"
            clearable
            prefix-icon="el-icon-search"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="是否正确" prop="isCorrect">
          <el-select v-model="queryParams.isCorrect" placeholder="请选择是否正确答案" clearable style="width: 140px">
            <el-option label="是" :value="0" />
            <el-option label="否" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card class="box-card" shadow="hover">
      <div slot="header" class="clearfix">
        <span class="card-title">选项详情列表</span>
        <div class="action-buttons">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['question:answer:export']"
          >导出</el-button>
          <el-button
            :type="showDeleted ? 'warning' : 'info'"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="toggleRecycleBin"
          >{{ showDeleted ? '返回列表' : '回收站' }}</el-button>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </div>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="groupedAnswerList"
        @selection-change="handleSelectionChange"
        border
        stripe
        highlight-current-row
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="题目ID" align="center" prop="questionId" width="80" />
        <el-table-column label="题目内容" align="left" prop="questionTitle" :show-overflow-tooltip="true" min-width="300">
          <template slot-scope="scope">
            <div class="question-content" v-html="scope.row.questionTitle"></div>
          </template>
        </el-table-column>
        <el-table-column label="选项内容" align="left" min-width="300">
          <template slot-scope="scope">
            <div v-for="(answer, index) in scope.row.answers" :key="answer.id" class="answer-item">
              <el-tag 
                :type="answer.isCorrect === 0 ? 'success' : 'info'"
                size="mini" 
                style="margin-right: 8px"
              >
                {{ String.fromCharCode(65 + index) }}
              </el-tag>
              <div class="answer-content" v-html="answer.content"></div>
              <div class="answer-actions">
                <template v-if="!showDeleted">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(answer)"
                    v-hasPermi="['question:answer:edit']"
                  >修改</el-button>
                  <el-divider direction="vertical"></el-divider>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(answer)"
                    v-hasPermi="['question:answer:remove']"
                  >删除</el-button>
                </template>
                <template v-else>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-refresh"
                    @click="handleRestore(answer)"
                    v-hasPermi="['question:answer:edit']"
                  >恢复</el-button>
                </template>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改答案对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item v-if="form.id" label="答案ID">
          <el-input v-model="form.id" disabled />
        </el-form-item>
        <el-form-item label="题目ID" prop="questionId">
          <el-input 
            v-model="form.questionId" 
            placeholder="请输入题目ID" 
            style="width: 200px"
            :disabled="form.id != null"
            @change="handleQuestionIdChange"
          />
        </el-form-item>
        <el-form-item label="题目内容">
          <div class="question-content" v-html="questionTitle"></div>
        </el-form-item>
        <el-form-item label="答案内容" prop="content">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="是否正确" prop="isCorrect">
          <el-select v-model="form.isCorrect" placeholder="请选择是否正确答案" style="width: 100%">
            <el-option label="是" :value="0" />
            <el-option label="否" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="isDeleted">
          <el-select v-model="form.isDeleted" placeholder="请选择状态" style="width: 100%">
            <el-option
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAnswer, getAnswer, delAnswer, addAnswer, updateAnswer } from "@/api/question/answer";
import { getQuestions } from "@/api/question/questions";

export default {
  name: "Answer",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 答案表格数据
      answerList: [],
      groupedAnswerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 5,  // 每页显示5道题
        questionId: null,
        title: null,
        isCorrect: null,
        isDeleted: '0'  // 默认显示未删除的数据
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        questionId: [
          { required: true, message: "题目ID不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "答案内容不能为空", trigger: "blur" }
        ],
        isCorrect: [
          { required: true, message: "请选择是否正确答案", trigger: "change" }
        ]
      },
      // 题目内容
      questionTitle: '',
      // 是否显示回收站
      showDeleted: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询答案列表 */
    getList() {
      this.loading = true;
      listAnswer({
        ...this.queryParams,
        pageNum: 1,  // 获取所有数据
        pageSize: 999999,
        isDeleted: this.queryParams.isDeleted
      }).then(response => {
        // 按题目ID分组
        const groupMap = new Map();
        response.rows.forEach(answer => {
          const questionId = answer.questionId;
          if (!groupMap.has(questionId)) {
            groupMap.set(questionId, {
              questionId: questionId,
              questionTitle: answer.dtQuestion?.title || '',
              answers: []
            });
          }
          groupMap.get(questionId).answers.push(answer);
        });

        // 将Map转为数组并对每组内的答案排序
        const allGroups = Array.from(groupMap.values()).map(group => ({
          ...group,
          answers: group.answers.sort((a, b) => a.id - b.id)
        }));

        // 前端分页，每页5道题
        const start = (this.queryParams.pageNum - 1) * 5;
        const end = start + 5;
        
        this.groupedAnswerList = allGroups.slice(start, end);
        this.total = allGroups.length;  // 总题目数
        this.loading = false;
      }).catch(() => {
        this.loading = false;
        this.groupedAnswerList = [];
        this.total = 0;
      });
    },
    /** 分组处理答案数据 */
    groupAnswers() {
      const groupMap = new Map();
      
      this.answerList.forEach(answer => {
        if (!groupMap.has(answer.questionId)) {
          groupMap.set(answer.questionId, {
            questionId: answer.questionId,
            questionTitle: answer.dtQuestion?.title || '',
            answers: []
          });
        }
        groupMap.get(answer.questionId).answers.push(answer);
      });

      // 将Map转为数组
      this.groupedAnswerList = Array.from(groupMap.values());
      
      // 对每组内的答案按isCorrect排序（正确答案在前）
      this.groupedAnswerList.forEach(group => {
        group.answers.sort((a, b) => a.isCorrect - b.isCorrect);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 重置表单 */
    reset() {
      this.form = {
        id: null,
        questionId: null,
        content: null,
        isCorrect: 1,
        isDeleted: 0
      };
      this.questionTitle = '';  // 重置题目内容
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.isDeleted = this.showDeleted ? '1' : '0';  // 保持回收站状态
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加答案";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getAnswer(id).then(response => {
        this.form = response.data;
        this.form.isDeleted = parseInt(this.form.isDeleted);
        this.form.isCorrect = parseInt(this.form.isCorrect);
        // 获取题目内容
        if (this.form.questionId) {
          this.handleQuestionIdChange(this.form.questionId);
        }
        this.open = true;
        this.title = "修改答案";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) return;

        // 添加 loading
        const loading = this.$loading({
          lock: true,
          text: '提交中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        // 检查该题目下是否已存在相同内容的选项（只检查未删除的记录）
        listAnswer({
          questionId: this.form.questionId,
          isDeleted: '0',
          pageSize: 999
        }).then(response => {
          const existingAnswer = response.rows.find(item => 
            item.questionId === this.form.questionId && 
            item.content === this.form.content && 
            item.id !== this.form.id
          );

          if (existingAnswer) {
            loading.close();
            this.$modal.msgError("该题目下已存在相同内容的选项");
            return;
          }

          // 检查该题目的选项数量是否超过限制（未删除的选项）
          const currentAnswers = response.rows.filter(item => 
            item.questionId === this.form.questionId && 
            item.id !== this.form.id
          );

          if (!this.form.id && currentAnswers.length >= 6) {
            loading.close();
            this.$modal.msgError("每道题最多只能有6个选项");
            return;
          }

          // 检查是否有正确答案（如果当前选项不是正确答案）
          if (this.form.isCorrect === 1) {
            const hasCorrectAnswer = currentAnswers.some(item => item.isCorrect === 0);
            if (!hasCorrectAnswer && currentAnswers.length > 0) {
              loading.close();
              this.$modal.msgError("请至少保留一个正确答案");
              return;
            }
          }

          // 通过所有检查，继续提交
          const request = this.form.id ? updateAnswer(this.form) : addAnswer(this.form);
          
          request.then(response => {
            loading.close();
            this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功");
            this.open = false;
            this.getList();
          }).catch(() => {
            loading.close();
            this.$modal.msgError("操作失败");
          });
        }).catch(() => {
          loading.close();
          this.$modal.msgError("操作失败");
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除答案编号为"' + ids + '"的数据项？').then(function() {
        return delAnswer(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('question/answer/export', {
        ...this.queryParams
      }, `answer_${new Date().getTime()}.xlsx`)
    },
    /** 题目ID变化时获取题目内容 */
    handleQuestionIdChange(value) {
      if (value) {
        getQuestions(value).then(response => {
          if (response.data) {
            this.questionTitle = response.data.title;
          } else {
            this.$modal.msgError("未找到相关题目");
            this.questionTitle = '';
          }
        }).catch(() => {
          this.questionTitle = '';
        });
      } else {
        this.questionTitle = '';
      }
    },
    /** 切换回收站显示状态 */
    toggleRecycleBin() {
      this.showDeleted = !this.showDeleted;
      // 重置分页参数
      this.queryParams = {
        ...this.queryParams,
        pageNum: 1,
        pageSize: 10,
        isDeleted: this.showDeleted ? '1' : '0'
      };
      // 重置选中状态
      this.ids = [];
      this.single = true;
      this.multiple = true;
      // 重新获取列表
      this.getList();
    },
    /** 恢复按钮操作 */
    handleRestore(row) {
      const id = row.id || this.ids;
      this.$modal.confirm('是否确认恢复选项编号为"' + id + '"的数据项？').then(async () => {
        // 获取选项详细信息
        const response = await getAnswer(id);
        // 修改状态为0（正常）
        const data = {
          ...response.data,
          isDeleted: 0
        };
        // 调用修改接口
        return updateAnswer(data);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("恢复成功");
      }).catch(() => {});
    },
  }
};
</script>

<style scoped>
.search-card {
  margin-bottom: 16px;
  border-radius: 4px;
}

.box-card {
  margin-bottom: 16px;
  border-radius: 4px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2f3d;
}

.action-buttons {
  float: right;
}

.question-content {
  padding: 8px 12px;
  line-height: 1.6;
  text-align: left;
  background-color: #f5f7fa;
  border-radius: 4px;
  min-height: 24px;
}

.answer-content {
  padding: 8px 12px;
  line-height: 1.6;
  text-align: left;
  background-color: #f0f9eb;
  border-radius: 4px;
  color: #67c23a;
}

.el-card {
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08) !important;
}

.el-card :deep(.el-card__header) {
  padding: 12px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fafafa;
}

.el-table {
  margin: 8px 0;
}

.el-table :deep(th) {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: 600;
}

.el-table :deep(td) {
  padding: 8px 0;
}

.el-tag {
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
}

.el-divider--vertical {
  margin: 0 8px;
}

/* 表格hover效果 */
.el-table :deep(tbody tr:hover) td {
  background-color: #f0f9eb !important;
}

/* 输入框图标颜色 */
.el-input :deep(.el-input__icon) {
  color: #909399;
}

/* 表单项间距 */
.el-form-item {
  margin-bottom: 16px;
}

.answer-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 8px;
  padding: 8px;
  background-color: #f8f9fa;
  border-radius: 4px;
  position: relative;
}

.answer-content {
  flex: 1;
  margin-left: 8px;
}

.answer-actions {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  display: none;
  background-color: #f8f9fa;
  padding: 0 8px;
}

.answer-item:hover .answer-actions {
  display: block;
}

.question-content {
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  line-height: 1.6;
}
</style>

